const { exec } = require('../db/mysql')
const getList = async (author ,keyword)=>{
    let sql =`select * from blogs where 1=1 `
    if(author){
        sql += `and author like '%${author}%' `
    }

    if(keyword){
        sql += `and title like '%${keyword}%' `
    }
    sql += `order by createtime desc;`
    console.log(sql);
    
    return await exec(sql)
}

const getDetail = (id)=>{
    console.log(id);
    
    let sql = `select * from blogs where id='${id}';`
    return exec(sql).then( listdata=>{
        console.log(JSON.stringify(listdata));
        
        return listdata[0]
    })
}

const newBlogs = (postdate)=>{
    const title = postdate.title
    const content = postdate.content
    const createtime = new Date().getTime()
    const author = postdate.author
    let sql = `insert into blogs (title,content,createtime,author) values ('${title}','${content}',${createtime},'${author}')`
    return exec(sql).then( date =>{
        return {
            id:date.insertId
        }
        console.log(JSON.stringify(date))
    })
}

const updateBlog = (id , postdate)=>{
    const title = postdate.title
    const content = postdate.content
    id = postdate.id
    const sql =`
                update blogs set title='${title}',content='${content}' where id=${id};
    `
    console.log(id,JSON.stringify('postdate',postdate));
    console.log(sql);
    
    return exec(sql).then( update =>{
        console.log(id,JSON.stringify(update))
        if(update.affectedRows > 0){//更新影响的行数大于0
            return true
        }
        return false
    })
}

const deleBlog = (id,author)=>{
    const sql =`
        delete from blogs where id=${id} and author='${author}';
    `
    return exec(sql).then( deleDate =>{
        console.log(id,JSON.stringify(deleDate))
        if(deleDate.affectedRows > 0){//更新影响的行数大于0
            return true
        }
        return false
    })
}

module.exports = {
    getList,
    getDetail,
    updateBlog,
    newBlogs,
    deleBlog
}